package com.qianjiangcloud.store.util;

import android.content.Context;
import android.graphics.Point;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.activity.AgentActivity;
import com.qianjiangcloud.store.ui.CircleFlowIndicator;
import com.qianjiangcloud.store.ui.FlowView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import com.qianjiangcloud.store.R;
import com.qianjiangcloud.store.libary.cache.MyImageLoader;

/**
 * 广告轮播图，高度随服务器返回数据变化
 * 主要传入参数
 * Context；String；float
 * 调用方法
 * getAdsViews(Context mContext, String json_str , float weight)；
 * 默认自动滚动，手动可以设置自动滚动和停止
 * 自动滚动调用方法：startAutoRun()
 * 停止滚动调用方法：stopAutoRun()
 * 滚动间隔时间，默认4秒
 * INTERVAL_AUTO_SNAP_FLOWVIEW = 4000L
 */
public class MainFragmentAdsUtils {
    private Point mScreenSize = null;
    private RelativeLayout adsFrameLayout = null;
    private View vi = null;
    private FlowView mTopAdsView;
    private Context context;
    private  String module_id;

    public View getAdsViews(Context mContext) {
        context = mContext;
        //创建布局
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        mScreenSize = Run.getScreenSize(windowManager);
        adsFrameLayout = new RelativeLayout(mContext);
        RelativeLayout.LayoutParams adsFrameLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        adsFrameLayout.setLayoutParams(adsFrameLayoutParams);
        vi = LayoutInflater.from(mContext).inflate(R.layout.main_ads_view, null);
        mTopAdsView = (FlowView) vi.findViewById(R.id.goods_detail_images);
        adsFrameLayout.addView(vi);
        //解析json
        // setUpView(mContext, json_str, weight, mTopAdsView);
        //parseHomeAdsJson(json_str, true ,mContext, mTopAdsArray,weight);
//        if(mTopAdsArray.size()>1) {
//            //设置自动滚动
//            startAutoRun();
//        }
        //设置自动滚动,此方法已经添加了一张图片不滚
        startAutoRun();
        return adsFrameLayout;
    }

    public void setUpView(String module_id,Context mContext, String json, float weight, View view) {
        // mTopAdsView = (FlowView) vi.findViewById(R.id.goods_detail_images);
        this.module_id=module_id;
        this.context = mContext;
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        mScreenSize = Run.getScreenSize(windowManager);
        this.mTopAdsView = (FlowView) view.findViewById(R.id.goods_detail_images);
        this.adsFrameLayout = (RelativeLayout) view;
        this.vi = ((RelativeLayout) view).getChildAt(0);
        parseHomeAdsJson(json, mContext, weight, mTopAdsView);
    }

    /**
     * 解析广告json
     */
    private void parseHomeAdsJson(String json_str, Context mContext, float weight, FlowView mTopAdsView) {
        ArrayList<JSONObject> mTopAdsArray = new ArrayList<JSONObject>();
        try {
            JSONObject all = new JSONObject(json_str);
            if (Run.checkRequestJson(mContext, all)) {
                JSONObject infoObject = all.getJSONObject("data");
                JSONArray child = infoObject.optJSONArray("info");
                if (child != null && child.length() > 0) {
                    mTopAdsArray.clear();
                    for (int i = 0; i < child.length(); i++) {
                        JSONObject topJson = child.getJSONObject(i);
                        mTopAdsArray.add(topJson);
                    }
                    if (mTopAdsArray.size() > 0) {
                        reloadMainView(false, weight, mContext, mTopAdsView, mTopAdsArray);
                    } else {
                        reloadMainView(true, weight, mContext, mTopAdsView, mTopAdsArray);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void reloadMainView(boolean isOutDate, float weight, Context mContext, FlowView mTopAdsView, ArrayList<JSONObject> mTopAdsArray) {
        if (mTopAdsArray != null && mTopAdsArray.size() > 0 && !isOutDate) {
//         添加轮播图
            mTopAdsView.setAdapter(new FlowAdapter(mContext, mTopAdsArray));
//           添加广告栏指示器
            if (mTopAdsArray.size() > 1) {
                addTopAdIndicator();
            }
            try {
//                根据长宽比来确定view高度
                float viewHeight = mScreenSize.x * weight;
                ViewGroup.LayoutParams params = mTopAdsView.getLayoutParams();
                params.height = (int) viewHeight;
                mTopAdsView.setLayoutParams(params);
                vi.setLayoutParams(params);
                adsFrameLayout.setLayoutParams(params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            mTopAdsView.setVisibility(View.GONE);
            vi.findViewById(R.id.main_top_adsview_indicator)
                    .setVisibility(View.GONE);
        }
    }

    private void addTopAdIndicator() {
        CircleFlowIndicator mTopAdsIndicator = (CircleFlowIndicator) adsFrameLayout
                .findViewById(R.id.goods_detail_images_indicator);
        mTopAdsIndicator.setVisibility(View.VISIBLE);
        mTopAdsView.setFlowIndicator(mTopAdsIndicator);
        mTopAdsIndicator.setViewFlow(mTopAdsView);
    }

    //商品大图浏览
    private class FlowAdapter extends BaseAdapter {
        private Context mContext;
        private ArrayList<JSONObject> mTopAdsArray;

        public FlowAdapter(Context context, ArrayList<JSONObject> mTopAdsArray) {
            this.mTopAdsArray = mTopAdsArray;
            this.mContext = context;
        }

        @Override
        public int getCount() {
            return mTopAdsArray == null ? 0 : mTopAdsArray.size();
        }

        @Override
        public JSONObject getItem(int position) {
            return mTopAdsArray.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                ImageView view = new ImageView(mContext);
                view.setLayoutParams(new AbsListView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                view.setScaleType(ImageView.ScaleType.CENTER_CROP);
                view.setOnClickListener(mAdViewClickListener);
                convertView = view;
            }

            JSONObject topAdsObject = getItem(position);
            Uri imageUri = Uri.parse(topAdsObject.optString("banner_img"));
            convertView.setTag(R.id.tag_object, topAdsObject);
            convertView.setTag(imageUri);
            MyImageLoader.displayDefaultImage(topAdsObject.optString("banner_img"), (ImageView) convertView);

            return convertView;
        }
    }

    private View.OnClickListener mAdViewClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getTag(R.id.tag_object) != null) {
                JSONObject data = (JSONObject) v.getTag(R.id.tag_object);
                String urlType = data.optString("link_type");
                if ("3".equals(urlType)) {
                    if (!TextUtils.isEmpty(data.optString("link_url"))) {
                        context.startActivity(AgentActivity.intentForFragment(
                                context, AgentActivity.FRAGMENT_GOODS_DETAIL)
                                .putExtra(Run.EXTRA_CLASS_ID,
                                        data.optString("link_url")).putExtra("title", data.optString("title")));
                    } else {
                        context.startActivity(AgentActivity.intentForFragment(
                                context, AgentActivity.FRAGMENT_GOODS_LIST)
                                .putExtra("module_id",module_id
                                ).putExtra("id", data.optString("id")).putExtra("isMoreGood", true).putExtra("title", data.optString("title")));
                    }
                } else if ("4".equals(urlType)) {
                    context.startActivity(AgentActivity.intentForFragment(context,
                            AgentActivity.FRAGMENT_ARTICLE_READER).putExtra(
                            "com.shopex.westore.EXTRA_URL", data.optString("link_url")).putExtra("title", data.optString("title")));
                } else if ("1".equals(urlType)) {
                    context.startActivity(AgentActivity
                            .intentForFragment(context,
                                    AgentActivity.FRAGMENT_GOODS_LIST)
                            .putExtra(Run.EXTRA_CLASS_ID,
                                    data.optString("link_url")).putExtra("title", data.optString("title")).putExtra("module",module_id).putExtra("id",data.optString("id"))
                    );
                } else if ("2".equals(urlType)) {
                    context.startActivity(AgentActivity
                            .intentForFragment(context,
                                    AgentActivity.FRAGMENT_GOODS_LIST)
                            .putExtra(Run.EXTRA_VITUAL_CATE,
                                    data.optString("link_url")).putExtra("title", data.optString("title")).putExtra("module",module_id).putExtra("id",data.optString("id")));
                }
            }
        }
    };

    /**
     * 设置自动滚动
     */
    public final int MESSAGE_AUTO_SNAP_FLOWVIEW = 1;
    private final long INTERVAL_AUTO_SNAP_FLOWVIEW = 5000L;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MESSAGE_AUTO_SNAP_FLOWVIEW) {
                mHandler.sendEmptyMessageDelayed(MESSAGE_AUTO_SNAP_FLOWVIEW, INTERVAL_AUTO_SNAP_FLOWVIEW);
                int count = mTopAdsView.getViewsCount();
                if (count > 1) {
                    int curScreen = mTopAdsView.getSelectedItemPosition();
                    if (curScreen >= (count - 1)) {
                        mTopAdsView.smoothScrollToScreen(0);

                    } else {
                        mTopAdsView.smoothScrollToScreen(curScreen + 1);
                    }
                }
            }
        }
    };

    //开始自动滚动
    public void startAutoRun() {
        mHandler.sendEmptyMessage(MESSAGE_AUTO_SNAP_FLOWVIEW);
    }

    ;

    //停止滚动
    public void stopAutoRun() {
        mHandler.removeMessages(MESSAGE_AUTO_SNAP_FLOWVIEW);
    }

    ;


}
